﻿using Microsoft.AspNetCore.Mvc;
using MVC系统mvc.Dto.AllocateDto;
using Newtonsoft.Json;
using WMS_MAV;

namespace MVC系统mvc.Controllers
{
    /// <summary>
    /// 调拨信息控制器
    /// </summary>
    public class AllocateController : Controller
    {
        /// <summary>
        /// 配置信息
        /// </summary>
        protected readonly IConfiguration configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration">配置信息</param>
        public AllocateController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        private string ExtractTokenFromHeader()
        {
            if (Request.Headers.TryGetValue("Authorization", out var tokenHeaderValues) && tokenHeaderValues.Count > 0)
            {
                string token = tokenHeaderValues.FirstOrDefault()?.TrimStart("Bearer ".ToCharArray());
                return !string.IsNullOrEmpty(token) ? token : null;
            }
            return null;
        }

        /// <summary>
        /// 添加调拨信息--视图
        /// </summary>
        /// <returns></returns>
        public IActionResult AddAllocateInfo()
        {
            return View();
        }

        /// <summary>
        /// 调拨列表--视图
        /// </summary>
        /// <returns></returns>
        public IActionResult ShowAllocateList()
        {
            return View();
        }

        /// <summary>
        /// 编辑调拨信息--视图
        /// </summary>
        /// <returns></returns>
        public IActionResult EditAllocate()
        {
            return View();
        }

        /// <summary>
        /// 创建生产计划--视图
        /// </summary>
        /// <returns></returns>
        public IActionResult CreatedProductionPlan()
        {
            return View();
        }

        /// <summary>
        /// 添加调拨信息
        /// </summary>
        /// <returns>JsonResult</returns>
        [HttpPost]
        public async Task<ActionResult> AddAllocateInfo(AddAllocateDto dto)
        {
            string token = ExtractTokenFromHeader();
            if (token == null)
            {
                return BadRequest("Authorization header missing or invalid.");
            }
            HttpClientWrapper httpClientWrapper = new HttpClientWrapper(token);
            string url = configuration["Url"] + "/purech/api/Allocate/CreadAllocateInfo";
            string list = JsonConvert.SerializeObject(dto);
            var response = await httpClientWrapper.PostAsync(url, list);
            return Json(response);
        }


        /// <summary>
        /// 调拨数据分页展示列表
        /// </summary>
        /// <param name="dto">dto</param>
        /// <returns>JsonResult</returns>
        [HttpGet]
        public async Task<ActionResult> GetAllocateList(ShowAllocateDto dto)
        {
            string token = ExtractTokenFromHeader();
            if (token == null)
            {
                return BadRequest("Authorization header missing or invalid.");
            }
            HttpClientWrapper httpClientWrapper = new HttpClientWrapper(token);
            string url = configuration["Url"] + "purech/api/Allocate/ShowAllocateList?AllocateNumber=" + dto.AllocateNumber + "&AllocateDate=" + dto.AllocateDate + "&AllocateStatus=" + dto.AllocateStatus + "&PageIndex=" + dto.PageIndex + "&PageSize=" + dto.PageSize;
            var response = await httpClientWrapper.GetAsync(url);
            return Json(response);
        }

        /// <summary>
        /// 删除调拨信息
        /// </summary>
        /// <returns>JsonResult</returns>
        [HttpPost]
        public async Task<ActionResult> DeleteAllocate(DeletedAllocateDto dto)
        {
            string token = ExtractTokenFromHeader();
            if (token == null)
            {
                return BadRequest("Authorization header missing or invalid.");
            }
            HttpClientWrapper httpClientWrapper = new HttpClientWrapper(token);
            string url = configuration["Url"] + "purech/api/Allocate/DeleteAllocate";
            var response = await httpClientWrapper.PostAsync(url, dto.Data);
            return Json(response);
        }

        /// <summary>
        /// 反填调拨信息
        /// </summary>
        /// <returns>JsonResult</returns>
        [HttpGet]
        public async Task<ActionResult> ReverseAllocate(ReverseFillingAllocateDto dto)
        {
            string token = ExtractTokenFromHeader();
            if (token == null)
            {
                return BadRequest("Authorization header missing or invalid.");
            }
            HttpClientWrapper httpClientWrapper = new HttpClientWrapper(token);
            string url = configuration["Url"] + "purech/api/Allocate/ReverseFillingAllocate?AllocateId=" + dto.AllocateId;
            var response = await httpClientWrapper.GetAsync(url);
            return Json(response);
        }

        /// <summary>
        /// 修改调拨信息
        /// </summary>
        /// <returns>JsonResult</returns>
        [HttpPost]
        public async Task<ActionResult> UpdateAllocate(UpdateAllocateDto objTwo)
        {
            string token = ExtractTokenFromHeader();
            if (token == null)
            {
                return BadRequest("Authorization header missing or invalid.");
            }
            HttpClientWrapper httpClientWrapper = new HttpClientWrapper(token);
            string url = configuration["Url"] + "purech/api/Allocate/UpdateAllocate";
            string list = JsonConvert.SerializeObject(objTwo);
            var response = await httpClientWrapper.PostAsync(url, list);
            return Json(response);
        }

        /// <summary>
        /// 修改调拨状态
        /// </summary>
        /// <returns>JsonResult</returns>
        [HttpPost]
        public async Task<ActionResult> UpdateAllocateStatus(UpdateStatusAllocateDto dto)
        {
            string token = ExtractTokenFromHeader();
            if (token == null)
            {
                return BadRequest("Authorization header missing or invalid.");
            }
            HttpClientWrapper httpClientWrapper = new HttpClientWrapper(token);
            string url = configuration["Url"] + "purech/api/Allocate/UpdateAllocateStatus";
            string list = JsonConvert.SerializeObject(dto);
            var response = await httpClientWrapper.PostAsync(url, list);
            return Json(response);
        }

        ///// <summary>
        ///// 导入调拨信息
        ///// </summary>
        ///// <param name="importFile"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult Import(HttpPostedFileBase importFile)
        //{
        //    if (importFile != null && importFile.ContentLength > 0)
        //    {
        //        if (importFile.FileName.EndsWith(".xlsx"))
        //        {
        //            // 将文件保存到服务器临时位置（可以根据实际情况调整路径策略）
        //            var filePath = Path.Combine(Server.MapPath("~/Temp"), Path.GetFileName(importFile.FileName));
        //            importFile.SaveAs(filePath);

        //            using (var package = new ExcelPackage(new FileInfo(filePath)))
        //            {
        //                var worksheet = package.Workbook.Worksheets[0]; // 假设读取第一个工作表
        //                int rowCount = worksheet.Dimension.Rows;
        //                for (int row = 2; row <= rowCount; row++) // 假设第一行是标题行，从第二行开始读取数据
        //                {
        //                    // 这里根据你的Excel文件结构读取具体单元格的数据，比如读取A列、B列的值
        //                    var cellAValue = worksheet.Cells[row, 1].Value.ToString();
        //                    var cellBValue = worksheet.Cells[row, 2].Value.ToString();
        //                    // 然后可以将读取的数据进行相应的业务处理，比如存入数据库等
        //                    // 示例：假设你有个服务层方法来处理数据持久化
        //                    YourServiceLayer.SaveData(cellAValue, cellBValue);
        //                }
        //            }
        //            // 文件处理完成后可以选择删除临时文件
        //            System.IO.File.Delete(filePath);
        //            return Content("导入成功");
        //        }
        //        else
        //        {
        //            return Content("请上传正确的Excel文件格式（.xlsx）");
        //        }
        //    }
        //    return Content("请选择要导入的文件");
        //}

    }
}
